<template>
  <a-form layout="vertical">
    <a-form-item label="标题" required>
      <a-input :value="data.title" placeholder="请输入标题" @update:value="v => update('title', v)" />
    </a-form-item>
    <a-form-item label="分类">
      <a-select :value="data.categoryId" style="width: 240px" allow-clear @change="v => update('categoryId', v)">
        <a-select-option v-for="c in categories" :key="c.id" :value="c.id">{{ c.name }}</a-select-option>
      </a-select>
    </a-form-item>
    <a-form-item label="标签">
      <a-select :value="data.tagIds" mode="multiple" style="width: 100%" allow-clear :max-tag-count="5" @change="v => update('tagIds', v)">
        <a-select-option v-for="t in tags" :key="t.id" :value="t.id">{{ t.name }}</a-select-option>
      </a-select>
    </a-form-item>
    <a-form-item label="摘要">
      <a-textarea :value="data.summary" :rows="3" placeholder="摘要（可选）" @update:value="v => update('summary', v)" />
    </a-form-item>
    <a-form-item label="封面URL">
      <a-input :value="data.coverImage" placeholder="https://..." @update:value="v => update('coverImage', v)" style="margin-bottom: 8px" />
      <div style="display:flex; gap:12px; align-items:center">
        <a-upload :before-upload="beforeUpload" :show-upload-list="false">
          <a-button>选择图片</a-button>
        </a-upload>
        <a-upload :custom-request="uploadToServer" :show-upload-list="false">
          <a-button type="primary">上传</a-button>
        </a-upload>
      </div>
      <div v-if="data.coverImage" style="margin-top: 8px">
        <a-image :src="data.coverImage" :preview="false" width="200" />
      </div>
    </a-form-item>
    <a-form-item label="状态">
      <a-select :value="data.status" @change="v => update('status', v)" :options="[
        { label: '草稿', value: 0 },
        { label: '发布', value: 1 },
        { label: '置顶', value: 2 }
      ]" />
    </a-form-item>
    <a-form-item label="内容（Markdown）">
      <SafeMarkdownEditor v-model="contentProxy" height="300px" />
    </a-form-item>
  </a-form>
</template>

<script setup lang="ts">
import type { CategoryVO, TagVO } from '@/types/api'
import { computed } from 'vue'
import SafeMarkdownEditor from './SafeMarkdownEditor.vue'

const props = defineProps<{
  modelValue: { title: string; summary?: string; coverImage?: string; content?: string; categoryId?: number; status?: number; tagIds?: number[] }
  categories: CategoryVO[]
  tags: TagVO[]
}>()

const emit = defineEmits<{ (e: 'update:modelValue', v: any): void }>()

const data = computed(() => props.modelValue || ({} as any))

function update<K extends keyof typeof data.value>(key: K, value: any) {
  emit('update:modelValue', { ...data.value, [key]: value })
}

const contentProxy = computed({
  get: () => {
    const content = data.value.content
    return content !== null && content !== undefined ? String(content) : ''
  },
  set: (v: string) => update('content' as any, v || '')
})

function beforeUpload(file: File) {
  const reader = new FileReader()
  reader.onload = () => { update('coverImage' as any, reader.result as string) }
  reader.readAsDataURL(file)
  return false
}

async function uploadToServer(options: any) {
  const form = new FormData()
  form.append('file', options.file as File)
  try {
    const resp = await fetch('/api/upload', { method: 'POST', body: form })
    const json = await resp.json().catch(() => null)
    const url = json?.data?.url || ''
    if (url) update('coverImage' as any, url)
    options.onSuccess?.(json, options.file)
  } catch (e) {
    options.onError?.(e)
  }
}
</script>

<style scoped>
</style>


